#include "ModbusDevice.hpp"

/***************************************************************
  *  @brief     ModbusDevice constructor
  *  @param     - port : The path of the device file 
  *             - baud : Baud rate
  *             - parity : Is there a check digit? 'N' or 'Y'
  *             - data_bit : Data bits. Usually 8 bits.
  *             - stop_bit : Stop bits. Usually 1 bit.
  *             - slave_id : Slave device id.
  *  @note      备注
  *  @author    
 **************************************************************/
ModbusDevice::ModbusDevice(const std::string &port, int baud, char parity, int data_bit, int stop_bit, int slave_id){
    this->ctx_ = modbus_new_rtu(port.c_str(),baud,parity,data_bit,stop_bit); // 创建modbus rtu这样一个句柄
    if (!this->ctx_) throw std::runtime_error("Failed to create Modbus context");
    modbus_set_slave(this->ctx_, slave_id); // 设置通信从机ID
    this->current_slave_id = slave_id;
    if (modbus_connect(this->ctx_) == -1)
        throw std::runtime_error("Failed to connect Modbus device");
}

ModbusDevice::~ModbusDevice(){
    if(this->ctx_){
        modbus_close(this->ctx_);
        modbus_free(this->ctx_);
    }
}

void ModbusDevice::SetSlaveID(int slave_id){
    modbus_set_slave(this->ctx_,slave_id);

}
void ModbusDevice::SetResponseTimeout(uint32_t sec,uint32_t usec){
    modbus_set_response_timeout(this->ctx_, sec, usec);
}

// 建立主机到Modbus中的通道，在modbus rtu 中相当于打开了串口，配置波特率等等相关配置
bool ModbusDevice::ModbusConnect(){
    return modbus_connect(this->ctx_) == -1 ? false : true;
}

bool ModbusDevice::ModbusReadRegisters(int addr, int len, uint16_t *dest){
    return modbus_read_registers(this->ctx_,addr,len,dest) == -1 ? false : true;

}